from rest_framework.authentication import BaseAuthentication
from util.Mytoken import mytoken
from rest_framework.response import Response
from zhxy.models import User


class JWTAuthenticationSelf(BaseAuthentication):
    def authenticate(self, request):
        # 获取token
        token_data = request.META.get("HTTP_AUTHORIZATION", None)
        if token_data:
            # 截取(获取到的token是 beaver加空格加token内容的形式，所以要用空格切割，获取后面的部分
            token_part = token_data.split(" ")[1]
            # 解码
            user_data = mytoken.verify_token(token_part)
            if user_data:
                userid = user_data["userid"]
                user = User.objects.get(id=userid)
                return user, token_part
        else:
            return None,None